package logic

import (
	"blog/models/cache"
	"blog/models/mysql"
	"blog/pkg"
	"context"
	"fmt"

	"blog/userrpc/internal/svc"
	"blog/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	if in.Username != "" {
		var us mysql.User
		mysql.DB.Debug().Where("username = ?", in.Username).Find(&us)
		if us.ID == 0 {
			return nil, fmt.Errorf("账号已不存在,无法登录")
		}
		if us.Password != pkg.MD5(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
		ca := cache.Rdb.Get(cache.Ctx, "captcha"+in.Username)
		if ca.Val() != in.CaptchaCode {
			return nil, fmt.Errorf("图形验证码错误")
		}
	}
	if in.Mobile != "" {
		var mo mysql.User
		mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&mo)
		if mo.ID == 0 {
			return nil, fmt.Errorf("手机号不存在,无法登录")
		}
		se := cache.Rdb.Get(cache.Ctx, "snedSms"+in.Mobile)
		if se.Val() != in.SendSmsCode {
			return nil, fmt.Errorf("手机验证码错误")
		}
	}
	return &userrpc.LoginResponse{}, nil
}
